/**
 * 应用级Token
 */

const Qs = require('querystring')
const Request = require('../request')
const { tokenLogger } = require('./util')
const { T_APP } = require('./dbHelper')

const REQ_URL = {
  'mirror': 'https://logintestlf.hwcloudtest.cn/oauth2/v2/token',
  'prod': 'https://login.cloud.huawei.com/oauth2/v2/token'
}

/**
 * @returns {Q.Promise<unknown>}
 */
async function genAppToken({ id, env }) {
  const rets = await T_APP.query(`id = ${id}`)
  if (rets.length <= 0) {
    throw new Error('传入的id未查到数据')
  }
  const { appid, appsecret } = rets[0]
  return Request.post(REQ_URL[`${env}`.toLowerCase()], Qs.stringify({
    grant_type: 'client_credentials',
    client_id: appid,
    client_secret: appsecret
  }), {
    'Content-Type': 'application/x-www-form-urlencoded'
  }).then(({ data }) => {
    console.log('=======================')
    console.log(JSON.stringify(data))
    console.log('=======================')
    return data
  }).catch(err => {
    // handle err
    throw new Error(`获取应用级token失败: ${err}; Error.response: ${err && err.response && JSON.stringify(err.response.data)}. Search string: ${this.searchStr}`)
  })
}

/**
 * 查找 app token list
 */
async function getAppList(env) {
  tokenLogger('info', 'query', `begin query table ${T_APP.tableName} with env is ${env}`)
  const envMapper = {
    'mirror': 0,
    'prod': 1
  }
  if (env !== undefined) {
    const tmpEnv = envMapper[`${env}`.toLowerCase()]
    if (tmpEnv !== undefined) {
      return await T_APP.query(`env = ${tmpEnv}`)
    }
  }
  return await T_APP.query()
}

module.exports = { genAppToken, getAppList }
